/**
 * 对复合页的简单测试。
 */
#include "test_tools.h"
#include <mm/early_alloc.h>
#include <mm/pages.h>
#include <mm/page_alloc.h>
#include <mm/compound_pages.h>
#include <mm/physical_area.h>
#include <mm/memory.h>
#include <mm/slab.h>
#include <mm/kmalloc.h>

/// 分配16MB
#define V_MEM_SIZE  (16UL << 20)

#define V_PAGE_ORDER 12

/// 第一个测试。
static void test1(void)
{
    /// 分配测试用的内存区域。
    void *v_mem = aligned_alloc(V_MEM_SIZE, V_MEM_SIZE);
    if (v_mem != NULL) {
        memset(v_mem, 0, V_MEM_SIZE);
    }
    unsigned long page_start = (VIRT_TO_PHY(v_mem) >> 12);
    unsigned long page_end = page_start + (V_MEM_SIZE >> 12);
    
    printf("%lu %lu\n", page_start, page_end);
    /// 初始化前期内存分配器。
    if (early_alloc_init(page_start, page_end, page_start, page_end, 12)) {
        LOG_TEST_FAIL("failed to initialize early_alloc!\n");
        while (1);
    }

    if (pages_init(VIRT_TO_PHY(v_mem), VIRT_TO_PHY(v_mem) + V_MEM_SIZE, 0)) {
        LOG_TEST_FAIL("failed to initialize page struct!\n");
        while (1);
    }
    if (set_pages_valid(VIRT_TO_PHY(v_mem), VIRT_TO_PHY(v_mem) + V_MEM_SIZE)) {
        LOG_TEST_FAIL("failed to make page struct valid!\n");
        while (1);
    }

    /// 添加内存区域。
    if (add_physical_area(VIRT_TO_PHY(v_mem), (6UL << 20))) {
        LOG_TEST_FAIL("failed to add physical area!\n");
        while (1);
    }
    if (add_physical_area(VIRT_TO_PHY(v_mem) + (6UL << 20), (2UL << 20))) {
        LOG_TEST_FAIL("failed to add physical area!\n");
        while (1);
    }

    /// 初始化pglist
    if (pglist_init(1)) {
        LOG_TEST_FAIL("failed to initialize pglists!\n");
        while (1);
    }

    /// 初始化内存区域结构体。
    if (mem_zones_init()) {
        LOG_TEST_FAIL("failed to initialize mem_zones!\n");
        while (1);
    }

    /// 激活伙伴系统。
    if (activate_buddy_system()) {
        LOG_TEST_FAIL("failed to activate buddy system!\n");
    } else {
        LOG_TEST_PASS("buddy system activated!\n");
    }

    /// 初始化 Slab 分配器。
    if (kmalloc_init()) {
        LOG_TEST_FAIL("failed to initialize kmalloc!\n");
    } else {
        LOG_TEST_PASS("kmalloc initialized!\n");
    }

    /// 这个模块的测试我全部在gdb中完成。
    while (1);
    free(v_mem);
}

int main(void)
{
    printf("** compound_pages.h test:\n");
    test1();
    return 0;
}
